// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext();
    const db = cloud.database();
    const _ = db.command;
    const QUEUE = db.collection("NWPU-Queue");
    const ORDER = db.collection("orderHistory");

    ORDER.where({
        _openid: wxContext.OPENID
    }).
        orderBy('datetime', 'desc').
        get().
        then(res => {
            let order = res.data[0];
            console.log("order: ", order);
            QUEUE.doc(order.domitory).
                get().
                then(res => {
                    res.data[order.floor].push(order._id);
                    console.log("queue", res.data);
                    let newdata = {};
                    for (let key in res.data) {
                        if (key == "_id" || key == "_openid") { continue; }
                        newdata[key] = res.data[key];
                    }
                    QUEUE.doc(order.domitory).
                        update({
                            data: newdata
                        })
                        .then(() => {
                            console.log("success update");
                        }).catch(err => {
                            console.error("error update\n", err); 
                        });
                }).catch(err => {
                    console.log("error get queue id\n", err);
                });
        }).catch(err => {
            console.log("error get order\n", err);
        });
}